package com.example.demo.entity;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import com.example.demo.service.security.Role;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
 * <p>
 * 
 * </p>
 *
 * @author ak
 * @since 2020-04-02
 */
@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @TableId(value = "u_id", type = IdType.AUTO)
    private Integer uId;

    @JsonProperty(value = "username")
    @NotEmpty(message = "用户名不能为空")
    private String uUsername;

    @JsonProperty(value = "password")
    @NotEmpty(message = "密码不能为空")
    private String uPassword;

    @NotEmpty(message = "密码不能为空")
    @TableField(exist = false)
    private String uPassword2;

    private String uRole;

    private String uCreate;

    private String uNick;

    private String uAvatar;

    private Integer uLv;

    /**
     * TableField注解表示该字段不是数据库表的字段
     * 存储角色权限信息
     */
    @TableField(exist = false)
    private Set<Role> roleSet=new HashSet<>();

    public void addRole(Role role){
        roleSet.add(role);
    }

    public String getToken(User user) {
        String token="";
        token= JWT.create().withAudience(String.valueOf(user.getUId()))
                .sign(Algorithm.HMAC256(user.getUPassword()));
        return token;
    }
}
